<?php

namespace backend\controllers;


use backend\components\BaseComponentController;
use common\components\DataHelper;
use common\models\Admin\Admin;
use common\models\AgentInfo\AgentInfo;
use common\models\PercentageItem\PercentageItem;
use common\models\Plug\Plug;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

class PlugsRunTotalController extends BaseComponentController
{
    /**
     * 列表
     */
    public function actionIndex()
    {
        $type = $this->get('type');
        $keyword = $this->get('keyword');
        $sDay = $this->get('start');
        $eDay = $this->get('end');
        if (empty($sDay) && empty($eDay)) {
            $sDay = $_GET['start'] = date('Y-m-d');
            $eDay = $_GET['end'] = date('Y-m-d');
        }

        $condition = [];
        if ($sDay) $condition[] = ['>=', 'created_date', $sDay];
        if ($eDay) $condition[] = ['<=', 'created_date', $eDay];
        if ($condition) array_unshift($condition, 'and');

        if (in_array($type, [1, 2, 3, 4]) && $keyword) {
            switch ($type) {
                case 1: // 代理商ID
                    $admin = Admin::findOne(['id' => (int)$keyword]);
                    $condition[] = ['=', 'agent_id', $admin ? $admin->id : null];
                    break;
                case 2: // 代理账号
                    $admin = Admin::findOne(['username' => $keyword]);
                    $condition[] = ['=', 'agent_id', $admin ? $admin->id : null];
                    break;
                case 3: // 代理商名称
                    $agentInfo = AgentInfo::findOne(['name' => $keyword]);
                    $condition[] = ['=', 'agent_id', $agentInfo ? $agentInfo->uid : null];
                    break;
                case 4: // 区域经理名称
                    $agentInfo = AgentInfo::findOne(['name' => $keyword]);
                    $condition[] = ['=', 'manager_id', $agentInfo ? $agentInfo->uid : null];
                    break;
            }
        }

        // 业务运行详情
        $plugsRunTotalQuery = PercentageItem::find()->select([
            'agent_id', 'manager_id', 'plug_id', 'SUM(upper_num) AS terminal_num_sum'
        ])->where($condition)->andWhere([
            "parent_agent" => 0
        ])->groupBy('manager_id,agent_id,plug_id');
        $page = DataHelper::getPage($plugsRunTotalQuery->count(), 20);
        $plugsRunTotalList = $plugsRunTotalQuery->offset($page->offset)->limit($page->limit)->asArray()->all();

        // 代理商
        $adminMap = [];
        $agentIds = ArrayHelper::getColumn($plugsRunTotalList, 'agent_id');
        $managerIds = ArrayHelper::getColumn($plugsRunTotalList, 'manager_id');
        if ($uIds = array_merge([], $agentIds ?: [], $managerIds ?: [])) {
            $adminMap = Admin::find()->where(['id' => $uIds])->indexBy('id')->asArray()->all();
        }

        // 插件
        $plugMap = Plug::find()->indexBy('id')->asArray()->all();

        return $this->render('index', [
            'plugsRunTotalList' => $plugsRunTotalList,
            'adminMap' => $adminMap,
            'plugMap' => $plugMap,
            'page' => $page,
        ]);
    }

    /**
     * 业务运行详情（折线图）
     */
    public function actionDetailLine()
    {
        $plugId = $this->get('plug_id');
        $agentId = $this->get('agent_id');
        $managerId = $this->get('manager_id');
        if (empty($plugId) || empty($agentId) || empty($managerId)) {
            $this->redirect(Url::to(['index']))->send();
        }
        $sDay = $this->get('start');
        $eDay = $this->get('end');
        if (empty($sDay) && empty($eDay)) {
            $sDay = $_GET['start'] = date('Y-m-d');
            $eDay = $_GET['end'] = date('Y-m-d');
        }

        $condition[] = ['=', 'agent_id', $agentId];
        $condition[] = ['=', 'manager_id', $managerId];
        $condition[] = ['=', 'plug_id', $plugId];
        if ($sDay) $condition[] = ['>=', 'created_date', $sDay];
        if ($eDay) $condition[] = ['<=', 'created_date', $eDay];
        if ($condition) array_unshift($condition, 'and');

        // 详情列表
        $plugsRunTotalList = PercentageItem::find()->select([
            'created_date',
            'SUM(upper_num) AS terminal_num_sum'
        ])->where($condition)->groupBy('manager_id,agent_id,plug_id,created_date')
            ->orderBy('created_date')
            ->asArray()->all();

        return $this->render('detail-line', [
            'plugsRunTotalList' => $plugsRunTotalList,
        ]);
    }

    /**
     * 业务运行详情（区域图）
     */
    public function actionDetailArea()
    {
        $plugId = $this->get('plug_id');
        $agentId = $this->get('agent_id');
        $managerId = $this->get('manager_id');
        if (empty($plugId) || empty($agentId) || empty($managerId)) {
            $this->redirect(Url::to(['index']))->send();
        }
        $sDay = $this->get('start');
        $eDay = $this->get('end');
        if (empty($sDay) && empty($eDay)) {
            $sDay = $_GET['start'] = date('Y-m-d');
            $eDay = $_GET['end'] = date('Y-m-d');
        }

        $condition[] = ['=', 'agent_id', $agentId];
        $condition[] = ['=', 'manager_id', $managerId];
        $condition[] = ['=', 'plug_id', $plugId];
        if ($sDay) $condition[] = ['>=', 'created_date', $sDay];
        if ($eDay) $condition[] = ['<=', 'created_date', $eDay];
        if ($condition) array_unshift($condition, 'and');

        // 县级详情列表
        $plugsRunTotalProvinceList = PercentageItem::find()->select([
            'province',
            'SUM(upper_num) AS terminal_num_sum'
        ])->where($condition)->groupBy('manager_id,agent_id,plug_id,province')->asArray()->all();

        // 市级详情列表
        $plugsRunTotalCityList = PercentageItem::find()->select([
            'city',
            'SUM(upper_num) AS terminal_num_sum'
        ])->where($condition)->groupBy('manager_id,agent_id,plug_id,city')->asArray()->all();

        return $this->render('detail-area', [
            'plugsRunTotalProvinceList' => $plugsRunTotalProvinceList,
            'plugsRunTotalCityList' => $plugsRunTotalCityList,
        ]);
    }

    /**
     * 分析
     */
    public function actionAnalysis()
    {
        $sDay = $this->get('start');
        $eDay = $this->get('end');
        if (empty($sDay) && empty($eDay)) {
            $sDay = $_GET['start'] = date('Y-m-d');
            $eDay = $_GET['end'] = date('Y-m-d');
        }

        $condition = [];
        if ($sDay) $condition[] = ['>=', 'created_date', $sDay];
        if ($eDay) $condition[] = ['<=', 'created_date', $eDay];
        if ($condition) array_unshift($condition, 'and');
        $condition[] = [
            "=","parent_agent",0
        ];
        // 县级详情列表
        $plugsRunTotalProvinceList = PercentageItem::find()->select([
            'province',
            'SUM(upper_num) AS terminal_num_sum'
        ])->where($condition)->groupBy('province')->asArray()->all();

        // 市级详情列表
        $plugsRunTotalCityList = PercentageItem::find()->select([
            'city',
            'SUM(upper_num) AS terminal_num_sum'
        ])->where($condition)->groupBy('city')->asArray()->all();

        return $this->render('analysis', [
            'plugsRunTotalProvinceList' => $plugsRunTotalProvinceList,
            'plugsRunTotalCityList' => $plugsRunTotalCityList,
        ]);
    }

}